package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioClient minioClient;
    @Autowired
    MinioProperties properties;
    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
       InputStream inputStream = file.getInputStream();
        String filenameExtension = StringUtils.getFilenameExtension(file.getOriginalFilename());
        String replace = UUID.randomUUID().toString().replace("-", "");

        String date = new DateTime().toString("yyyy/MM/dd/");
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(properties.getBucketName())
                .object(date+replace+"."+filenameExtension)
                .stream(inputStream, file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        String url = properties.getEndpoint()+"/"+properties.getBucketName()+"/"+date+replace+"."+filenameExtension;
        return url;
    }
}
